<template>
  <div class="channel-container">
    <el-card class="query-card">
      <el-form :inline="true" class="query-form">
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="chart-card">
      <template #header>
        <span>渠道线索有效率分析</span>
      </template>
      <div ref="totalChannelChart" class="chart"></div>
      <div ref="lineChart" class="chart" style="margin-top: 30px;"></div>
      <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="channelName" label="渠道名称" />
        <el-table-column prop="clueCount" label="线索数量" />
        <el-table-column prop="clueValidRate" label="线索有效率" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts' // Re-import echarts
import { Search, Refresh } from '@element-plus/icons-vue'
import request from '@/utils/request'
import axios from 'axios'
import { getChannelAnalysis } from '@/api/tienchin/channel'

const dateRange = ref([])
const totalChannelChart = ref(null)
let totalChannelChartInstance = null
const tableData = ref([])
const lineChart = ref(null)
let lineChartInstance = null

// 模拟数据获取
const fetchChartData = async (params = {}) => {
  try {
    const res = await getChannelAnalysis(params);
    const rawData = res.data || [];
    // 饼图渲染全部数据
    const totalChannelData = rawData.map(item => ({
      value: item.clueCount || 0,
      name: item.channelName
    }));
    // 图例只显示前15个
    const legendData = rawData.slice(0, 15).map(item => item.channelName);
    // 表格显示全部数据
    tableData.value = rawData.map(item => ({
      channelName: item.channelName,
      clueCount: item.clueCount || 0,
      clueValidRate: item.clueValidRate !== undefined ? item.clueValidRate : 0
    }));

    if (totalChannelChartInstance) {
      totalChannelChartInstance.setOption({
        title: {
          text: '渠道线索数量分布',
          left: 'center',
          top: 20
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: '0%',
          top: 'middle',
          data: legendData // 只显示前15个
        },
        series: [
          {
            name: '线索数量',
            type: 'pie',
            radius: '60%',
            center: ['50%', '55%'],
            data: totalChannelData,
            label: {
              show: true,
              formatter: '{b}'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    }

    // 折线图渲染
    if (lineChartInstance) {
      lineChartInstance.setOption({
        title: {
          text: '渠道线索数量趋势',
          left: 'center',
          top: 20
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: rawData.map(item => item.channelName)
        },
        yAxis: {
          type: 'value',
          name: '线索数量'
        },
        series: [
          {
            name: '线索数量',
            type: 'line',
            data: rawData.map(item => item.remark || 1),
            smooth: true
          }
        ]
      });
    }
  } catch (error) {
    console.error('获取渠道数据失败', error);
  }
};

function formatDate(val) {
  if (!val) return '';
  if (typeof val === 'string') return val.slice(0, 10);
  if (val instanceof Date) {
    const y = val.getFullYear();
    const m = (val.getMonth() + 1).toString().padStart(2, '0');
    const d = val.getDate().toString().padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
  return '';
}

// 搜索按钮事件
const handleQuery = () => {
  let params = {};
  if (dateRange.value && dateRange.value.length === 2) {
    const start = formatDate(dateRange.value[0]) + ' 12:00:00';
    const end = formatDate(dateRange.value[1]) + ' 12:00:00';
    params['dateRange[0]'] = start;
    params['dateRange[1]'] = end;
    params['params[beginTime]'] = start;
    params['params[endTime]'] = end;
  }
  fetchChartData(params);
}

// 重置按钮事件
const resetQuery = () => {
  dateRange.value = [];
  fetchChartData();
}

onMounted(() => {
  // 页面加载时的初始化逻辑
  nextTick(() => {
    if (totalChannelChart.value) {
      initTotalChannelChart();
    }
    if (lineChart.value) {
      lineChartInstance = echarts.init(lineChart.value);
    }
    fetchChartData(); // 首次加载时获取数据
  });

  // 强制设置背景，以覆盖可能的后期加载样式
  setTimeout(() => {
    if (document.body) {
      document.body.style.backgroundColor = 'transparent';
      document.body.style.padding = '0';
      document.body.style.margin = '0';
    }
    if (document.documentElement) {
      document.documentElement.style.backgroundColor = 'transparent';
      document.documentElement.style.padding = '0';
      document.documentElement.style.margin = '0';
    }
    const appElement = document.getElementById('app');
    if (appElement) {
      appElement.style.backgroundColor = 'transparent';
      appElement.style.padding = '0';
      appElement.style.margin = '0';
    }
  }, 0);
})

onBeforeUnmount(() => {
  // 恢复原始样式
  if (totalChannelChartInstance) {
    totalChannelChartInstance.dispose();
  }
  if (lineChartInstance) {
    lineChartInstance.dispose();
  }
  if (document.body) {
    document.body.style.backgroundColor = '';
    document.body.style.padding = '';
    document.body.style.margin = '';
  }
  if (document.documentElement) {
    document.documentElement.style.backgroundColor = '';
    document.documentElement.style.padding = '';
    document.documentElement.style.margin = '';
  }
  const appElement = document.getElementById('app');
  if (appElement) {
    appElement.style.backgroundColor = '';
    appElement.style.padding = '';
    appElement.style.margin = '';
  }
})

// 初始化渠道总数分析图表 (饼图)
const initTotalChannelChart = () => {
  totalChannelChartInstance = echarts.init(totalChannelChart.value);
  // 初始化时不设置数据，数据由 fetchChartData 设置
  totalChannelChartInstance.setOption({
    title: {
      text: '渠道线索数量分布',
      left: 'center',
      top: 20
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: '0%',
      top: 'middle'
    },
    series: [
      {
        name: '线索数量',
        type: 'pie',
        radius: '60%',
        center: ['50%', '55%'],
        data: [],
        label: {
          show: true,
          formatter: '{b}'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
};

</script>

<style lang="scss" scoped>
.channel-container {
  padding: 0;
  margin: 0;
  background-color: transparent;
  
  /* 强制移除el-card的默认背景、边框和阴影 */
  :deep(.el-card) {
    background-color: transparent !important;
    border: none !important;
    box-shadow: none !important;
  }

  .query-card {
    margin-bottom: 0;
    padding: 0;
    background-color: transparent !important;
    border: none !important;
    box-shadow: none !important;

    .query-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  
  .chart-card {
    margin-bottom: 20px; // Ensure there's some space below the chart card
    padding: 0; // Remove default padding for the chart card
    background-color: transparent !important; // Ensure transparent background for chart card
    border: none !important; // Remove border for chart card
    box-shadow: none !important; // Remove shadow for chart card

    .card-header {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding: 14px 15px 7px; // Adjust padding to match el-card__header default
      min-height: 40px; // Adjust min-height to match el-card__header default
      font-size: 15px; // Match font-size from .form-header
      color: #6379bb; // Match color from .form-header
      border-bottom: 1px solid #ddd; // Match border-bottom from .form-header
      margin: 0 0 15px 0; // Adjust margin below header
    }
    
    .chart {
      height: 400px; // Ensure chart has enough height
      width: 100%; // Ensure chart takes full width
      /* border: 2px solid red; // 去掉调试用的红色边框 */
    }
  }
}
</style>

<style lang="scss"> /* This block is NOT scoped */
/* If direct JS manipulation works, this can be removed. */
/*
body.no-page-background {
  background-color: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
}
*/
</style>